<template>
  <div class="ret-container">
    <div class="middle_box">
      <el-form
        ref="loginForm"
        :model="loginForm"
        :rules="loginRules"
        class="ret-form"
        auto-complete="on"
        label-position="left"
      >
        <div class="ret-container-tex">
          <h1 class="title">涉药物物流运输管理</h1>
          <h5 class="text">让涉药物流变得安全而简单</h5>
        </div>
        <el-form-item prop="corporate_name">
          <div class="verification">
            <span>* 公司名称：</span>
            <el-input
              v-model="loginForm.corporate_name"
              maxlength="16"
              placeholder="公司名称(注：与营业执照上的名字一致)"
            />
          </div>
        </el-form-item>
        <!-- 营业执照号 -->
        <el-form-item prop="business_license_number">
          <div class="verification">
            <span>* 营业执照号：</span>
            <el-input
              v-model="loginForm.business_license_number"
              placeholder="营业执照号"
            />
          </div>
        </el-form-item>
        <!-- 文件上传框 -->
        <div class="uploadbox">
          <div class="verification">
            <span style="width: 110px">* 上传文件：</span>
            <el-upload
              ref="upload_img"
              action
              multiple
              :auto-upload="false"
              list-type="picture-card"
              :before-remove="beforeRemove"
              :on-preview="handlePreview"
              :on-remove="
                (file, fileList) => {
                  handleRemove(file, fileList, 18);
                }
              "
              :on-change="
                (file, fileList) => {
                  handleChange(file, fileList, 18);
                }
              "
              :file-list="fileList"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
          </div>
        </div>
        <div>
          <!-- 个人信息 -->
          <div class="personal">
            <h5 class="h5personal">个人信息</h5>
            <el-form-item prop="name">
              <div class="verification">
                <span>* 用户名称：</span>
                <el-input
                  ref="username"
                  v-model="loginForm.name"
                  placeholder="用户名"
                  type="text"
                />
              </div>
            </el-form-item>
            <el-form-item prop="password1">
              <div class="verification">
                <span>* 密码：</span>
                <el-input
                  v-model="loginForm.password1"
                  maxlength="16"
                  placeholder="最低需要6位，且同时包含数字，字母"
                  type="text"
                />
              </div>
            </el-form-item>
            <el-form-item prop="password2">
              <div class="verification">
                <span>* 确认密码：</span>
                <el-input
                  v-model="loginForm.password2"
                  maxlength="16"
                  placeholder="确认密码"
                />
              </div>
            </el-form-item>
            <el-form-item prop="mobile">
              <div class="verification">
                <span>* 用户电话：</span>
                <el-input
                  v-model="loginForm.mobile"
                  maxlength="11"
                  placeholder="11位手机号"
                />
              </div>
            </el-form-item>
            <div>
              <el-form-item prop="mobile_captcha">
                <div class="verification" style="float: left">
                  <span style="width: 108px">* 手机验证码：</span>

                  <el-input
                    v-model="loginForm.mobile_captcha"
                    class="ret-authCode"
                    maxlength="8"
                    placeholder="验证码"
                  />
                </div>
                <el-button
                  :class="{ 'disabled-style': getCodeBtnDisable }"
                  :disabled="getCodeBtnDisable"
                  @click="getCode"
                  style="margin-top: 11px"
                  >{{ codeBtnWord }}
                </el-button>
              </el-form-item>
            </div>
          </div>
          <el-row type="flex" justify="space-between">
            <el-col :span="10">
              <el-button
                :loading="loading"
                class="ret-button"
                @click.native.prevent="handleLogin"
                >注册</el-button
              >
            </el-col>
            <el-col :span="9">
              <el-link :underline="false" @click="jumptTo"
                >使用已有账号登录</el-link
              >
            </el-col>
          </el-row>
          <template />
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
import { getRegist, getMobile, testRegister } from "@/api/user";
import "./index.scss";
import axios from "axios";
import { uploading } from "../material/common/common";
import md5 from "js-md5";

export default {
  name: "Login",

  data() {
    // 密码验证
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.loginForm.password1 !== "") {
          this.$refs.loginForm.validateField("affirm");
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.loginForm.password1) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      actionUrl: "", // 解决跨域
      codeBtnWord: "获取验证码", // 获取验证码按钮文字
      waitTime: 61, // 获取验证码按钮失效时间
      input: "", // 文件上传
      loading: false,
      fileList: [], // 上传得文件信息
      redirect: undefined,
      ingaplod: [],
      loginForm: {
        image_file: [], // 图片信息
        file_name: "123456.pnj",
        corporate_name: "", // 公司名
        business_license_number: "", //营业执照
        name: "", // 用户名
        password1: "", // 密码
        password2: "", // 确认密码
        mobile: "", // 手机号
        mobile_captcha: "", // 验证码
      },
      loginRules: {
        corporate_name: [
          { required: true, message: "请输入公司名称", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3到 10 个字符", trigger: "blur" },
        ],
        // 用户名
        name: [{ required: true, message: "请输入用户名", trigger: "blur" }],
        business_license_number: [
          { required: true, message: "请填写营业执照", trigger: "blur" },
        ],
        // 密码
        password1: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            required: true,
            pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/,
            message: "输入6-20位英文字母、数字且字母，数字，至少包含两种",
            trigger: "blur",
          },
        ],
        // 确认密码
        password2: [
          { required: true, message: "请确认密码", trigger: "blur" },
          {
            min: 6,
            max: 16,
            message: "长度在 6到 20 个字符",
            trigger: "blur",
          },
          { validator: validatePass2, trigger: "blur", required: true },
        ],
        //  验证码
        mobile_captcha: [
          { required: true, message: "请输入验证码", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3到 10 个数字", trigger: "blur" },
        ],
        // 手机号
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            required: true,
            pattern: /^1[3456789]\d{9}$/,
            message: "请输入正确11位手机号格式",
            trigger: "blur",
          },
        ],
      },
      fileList: [], //上传的图片文件
    };
  },
  computed: {
    // 用于校验手机号码格式是否正确
    phoneNumberStyle() {
      const reg = /^1[3456789]\d{9}$/;
      if (!reg.test(this.loginForm.mobile)) {
        return false;
      }
      return true;
    },
    // 控制获取验证码按钮是否可点击
    getCodeBtnDisable: {
      get() {
        if (this.waitTime === 61) {
          const reg = /^1[3456789]\d{9}$/;
          if (
            reg.test(this.loginForm.mobile) &&
            this.loginForm.mobile.length === 11
          ) {
            return false;
          }
          return true;
        }
        return true;
      },
      // 注意：因为计算属性本身没有set方法，不支持在方法中进行修改，而下面我要进行这个操作，所以需要手动添加
      set() {},
    },
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true,
    },
  },
  created() {
    this.actionUrl = "/api/auth/upload_file"; // 解决跨域
  },
  methods: {
    //上传图片的
    handleChange(file, fileList, type) {
      this.fileList = fileList;
      var filelist = file.raw; //文件
      var filename = file.raw.uid + file.raw.name; //通过 uid和name组成文件的名字
      // console.log(file.type, 123124);
      uploading(filelist, filename, type)
        .then((res) => {
          // console.log(res, "+++++++++=");
          this.loginForm.image_file = res.res.requestUrls[0];
        })
        .catch((error) => {
          this.$message({
            type: "error",
            message: "图片过大,上传失败",
          });
        });
    },
    handleRemove(file, fileList) {
      const index = this.loginForm.image_file.findIndex(
        (item) => item.uid === file.uid
      );
      index > -1 && this.loginForm.image_file.splice(index, 1);
    },
    handlePreview(file) {
      // console.log(file, "------------------------------------");
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    // 跳转
    jumptTo() {
      this.$router.push("/login");
    },
    // 发送验证码
    getCode() {
      if (this.phoneNumberStyle) {
        // 调用获取短信验证码接口

        getMobile({ phone: this.loginForm.mobile }).then((res) => {
          this.$message({
            message: "验证码已发送，请稍候...",
            type: "success",
            center: true,
          });
        });
        // 因为下面用到了定时器，需要保存this指向
        const that = this;
        that.waitTime--;
        that.getCodeBtnDisable = true;
        this.codeBtnWord = `${this.waitTime}s 后重新获取`;
        const timer = setInterval(function () {
          if (that.waitTime > 1) {
            that.waitTime--;
            that.codeBtnWord = `${that.waitTime}s 后重新获取`;
          } else {
            clearInterval(timer);
            that.codeBtnWord = "获取验证码";
            that.getCodeBtnDisable = false;
            that.waitTime = 61;
          }
        }, 1000);
      }
    },
    // 获取图片
    handleTestSuccess(file) {
      this.ingaplod = file;
    },
    // 点击注册
    handleLogin() {
      this.$refs.loginForm.validate(async (isOK) => {
        if (isOK) {
          let obj = {
            name: this.loginForm.corporate_name,
            bussiness_license: String(this.loginForm.image_file),
            bussiness_license_number: this.loginForm.business_license_number,
            username: this.loginForm.name,
            password: md5(this.loginForm.password2),
            sms_code: this.loginForm.mobile_captcha,
            mobile: this.loginForm.mobile,
          };
          // const formData = new FormData();
          // formData.append("image_file", this.ingaplod.file);
          // formData.append("name", this.loginForm.name);
          // formData.append("password1", this.loginForm.password1);
          // formData.append("password2", this.loginForm.password2);
          // formData.append("corporate_name", this.loginForm.corporate_name);
          // formData.append(
          //   "business_license_number",
          //   this.loginForm.business_license_number
          // );
          // formData.append("mobile", this.loginForm.mobile);
          // formData.append("mobile_captcha", this.loginForm.mobile_captcha);
          // let result1 = await testRegister({ username: this.loginForm.name });
          // if (result1.data === 0) {
          //   getRegist(obj)
          //     .then((res) => {
          //       if (res.code === 10000) {
          //         this.loginForm = "";
          //         this.$message.success("注册成功");
          //         this.$router.push({ path: "/login" });
          //       } else {
          //         this.$message({
          //           type: "warning",
          //           message: `${res.message}`,
          //         });
          //       }
          //     })
          //     .catch((error) => {});
          // } else {
          //   this.$message({
          //     type: "error",
          //     message: "该用户名已经被注册",
          //   });
          // }
          getRegist(obj)
            .then((res) => {
              if (res.code === 10000) {
                this.loginForm = "";
                this.$message.success("注册成功");
                this.$router.push({ path: "/login" });
              } else {
                this.$message({
                  type: "warning",
                  message: `${res.message}`,
                });
              }
            })
            .catch((error) => {});
        }
      });
    },
  },
};
</script>
<style lang="less" scoped>
/deep/.el-upload-list--picture-card .el-upload-list__item {
  width: 95px !important;
  height: 95px !important;
}
/deep/.el-button.disabled-style {
  height: 30px !important;
  margin-top: 10px !important;
}
// .el-input{
//   width: 200px !important;
// }
</style>

